package com.link.base.core.RSAUtils;


import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

/**
 * AES工具类
 *
 * @author 黄龙建
 * @date 2020/1/8 3:11 下午
 */
public class AESUtils {

    /**
     * @param rawKey
     *            密钥
     * @param clearPwd
     *            明文字符串
     * @return 密文编码字符串
     */
    private static byte[] encrypt(byte[] rawKey, String clearPwd) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(rawKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            return cipher.doFinal(clearPwd.getBytes());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     *
     * @param strKey
     * @param clearPwd
     * @return 字符串
     * @throws Exception
     * @Comments aes 加密转base64 返回
     */
    public static String encryptBase64(String strKey, String clearPwd) throws Exception {
        byte[] rawKey = getRawKey(strKey.getBytes());
        return Base64Utils.encode(encrypt(rawKey, clearPwd));
    }

    /**
     * @param encrypted
     *            密文字节数组
     * @param rawKey
     *            密钥
     * @return 解密后的字符串
     */
    private static String decrypt(byte[] encrypted, byte[] rawKey) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(rawKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decrypted = cipher.doFinal(encrypted);
            return new String(decrypted);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * @auther HuangLJ
     * @date 2018-12-26 20:49
     * @param encryptStr base64加密过的密文
     * @param strKey 秘钥
     * @return 解密之后的字符串
     * @throws Exception 报错
     * @comments
     */
    public static String decryptBase64(String encryptStr, String strKey) throws Exception {
        byte[] rawKey = getRawKey(strKey.getBytes());
        byte[] encrypted = Base64Utils.decode(encryptStr);
        return decrypt(encrypted, rawKey);
    }

    /**
     * @param seed 种子数据
     * @return 密钥数据
     */
    private static byte[] getRawKey(byte[] seed) {
        byte[] rawKey = null;
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(seed);
            // AES加密数据块分组长度必须为128比特，密钥长度可以是128比特、192比特、256比特中的任意一个
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            rawKey = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return rawKey;
    }
}
